<?php


namespace app\api\controller;


use app\common\controller\CommonBase;
use app\common\model\Agent;
use app\common\model\Parkinfo;
use app\common\model\Parklog;
use app\common\model\Paylog;
use etpcar\EtpCar;
use Wechat\Wxobjopen;

class CarPay extends CommonBase
{
    //入场记录支付信息
    public function inpay($params, $parkinfo)
    {
        $Agent = new Agent();
        $agentinfo = $Agent->where(['id' => $parkinfo['agentid']])->find();
        $weObj = new Wxobjopen(['partnerkey' => $agentinfo['machkey']]);
        $scene_info['scene_info'] = [
            "start_time" => date('YmdHis', strtotime($params['InTime'])),
            "plate_number" => $params['CarNo'],
            "car_type" => "小型车",
            "parking_name" => $parkinfo['parktitle'],
            "free_time" => "0",
        ];
        $arrdata = array(
            "appid" => $agentinfo['appid'],
            "mch_id" => $agentinfo['machid'],
            'sub_appid' => $parkinfo['micro_appid'],
            "sub_mch_id" => $parkinfo['machid'],
            "nonce_str" => $weObj->generateNonceStr(),
            "sign_type" => "HMAC-SHA256",
            "version" => "2.0",
            "trade_scene" => "PARKING",
            "scene_info" => json_encode($scene_info, JSON_UNESCAPED_UNICODE)
        );
        $urls = "https://api.mch.weixin.qq.com/vehicle/partnerpay/notification";
        $pay_xml = $weObj->createWxPackageXml($arrdata);
        $pay_xml = $weObj->SendPost($urls, $pay_xml);

        file_put_contents('/data2/html/apis/3.txt', "[" . date('Y-m-d H:i:s') . "]" . "入场:" . json_encode($pay_xml) . PHP_EOL, 8);

        if ($pay_xml['return_code'] == "SUCCESS") {
            if ($pay_xml['result_code'] == "SUCCESS") {
                $re_param['return_code'] = "SUCCESS";
                $re_param['return_msg'] = "传递微信无感成功";
                //此处需要记录是否能无感支付

            } else {
                $re_param['return_code'] = "FAIL";
                $re_param['return_msg'] = $pay_xml['err_code_des'];
            }
        }
        return $re_param;

    }

    public function get_car_fee($param, $parkinfo)
    {

        $last_log_id = $this->getcarlastid($parkinfo['id'], $param['key1value']);
        $Parklog = new Parklog();
        $parklog = $Parklog->where(['parkid' => $parkinfo['id'], 'id' => $last_log_id])->order('id desc')->find();

        $option = [
            'key' => $parkinfo['parkkey'],
            'parkno' => $parkinfo['parkno'],
        ];

        //判断支付方式(无感);
        //无感支付
        $re_param = [];
        if ($parkinfo['is_open_wxwg'] == "Y") {

            if ($parklog['is_wx_wg'] == "Y" && $parklog['paystatus'] == "N") {

                $params['paytype'] = "autopay";
                $params['carno'] = $parklog['carno'];
                $params['parksize'] = $parkinfo['parksize'];
                $params['channel'] = 'weixin';

                $Carapi = new EtpCar($option);
                $res = $Carapi->get_tmp_fee($params);
                if ($res['ReMsg']['ErrNo'] == "0000") {
                    //加入支付记录
                    $out_trade_no = "Park_01" . date('YmdHis') . rand(10000, 99999);
                    $s_data['sysid'] = $parkinfo['sysid'];
                    $s_data['agentid'] = $parkinfo['agentid'];
                    $s_data['parkid'] = $parkinfo['id'];
                    $s_data['oid'] = $parklog['id'];
                    $s_data['feecate'] = $res['FeeType'];
                    $s_data['orderid'] = $out_trade_no;
                    $s_data['orderno'] = $res['OrderNo'];
                    $s_data['pay_status'] = "N";
                    $s_data['total_fee'] = $res['PayFee'] / 100;
                    $s_data['pay_status'] = "N";
                    $s_data['add_time'] = time();
                    $Paylog = new Paylog();
                    $id = $Paylog->save($s_data);
                    $Parklog->save(['orderno' => $res['OrderNo'], 'total_fee' => $res['PayFee'] / 100, 'orderid' => $out_trade_no], ['id' => $parklog['id']]);

                    $re_param = $this->wxvehiclepay($parklog['id'], $parkinfo);
                }
            } else {
                //逻辑错误暂时停用
//                $Carapi = new EtpCar($option);
//                $params['machno'] = $parklog['outno'];
//                $params['text'] = "停车超时,请支付超时费用";
//                $res = $Carapi->up_voice($params);
                $re_param['return_code'] = "FAIL";
                $re_param['return_msg'] = "FAIL";
            }
        }
        return $re_param;

    }

    public function wxvehiclepay($parklogid, $parkinfo)
    {
        $Parklog = new Parklog();
        $parklog = $Parklog->where(['id' => $parklogid])->find();
        $Agent = new Agent();
        $agentinfo = $Agent->where(['id' => $parkinfo['agentid']])->find();
        $weObj = new Wxobjopen(['partnerkey' => $agentinfo['machkey']]);
        $scene_info['scene_info'] = [
            "start_time" => date('YmdHis', strtotime($parklog['intime'])),
            "end_time" => date('YmdHis'),
            "charging_time" => time() - strtotime($parklog['intime']),
            "plate_number" => $parklog['carno'],
            "car_type" => "小型车",
            "parking_name" => $parkinfo['parktitle'],
        ];

        //创建支付记录

        $arrdata = array(
            "appid" => $agentinfo['appid'],
            "mch_id" => $agentinfo['machid'],
            'sub_appid' => $parkinfo['micro_appid'],
            "sub_mch_id" => $parkinfo['machid'],
            "nonce_str" => $weObj->generateNonceStr(),
            "sign_type" => "HMAC-SHA256",
            "body" => "停车代扣",
            "attach" => "",
            "out_trade_no" => $parklog['orderid'],
            "total_fee" => $parklog['total_fee'] * 100,
            "version" => "2.0",
            "trade_scene" => "PARKING",
            "spbill_create_ip" => "222.88.142.170",
            "notify_url" => "https://apis.wunengkeji.com/carapi.php/wxvehiclenotify",
            "trade_type" => "PAP",//固定值委托代扣支付
            "scene_info" => json_encode($scene_info, JSON_UNESCAPED_UNICODE)
        );
        $urls = "https://api.mch.weixin.qq.com/vehicle/partnerpay/payapply";
        $pay_xml = $weObj->createWxPackageXml($arrdata);
        $pay_xml = $weObj->SendPost($urls, $pay_xml);
        file_put_contents('/data2/html/apis/3.txt', "[" . date('Y-m-d H:i:s') . "]" . "出场支付:" . json_encode($pay_xml) . PHP_EOL, 8);

        if ($pay_xml['return_code'] == "SUCCESS") {
            if ($pay_xml['result_code'] == "SUCCESS") {

                $re_param = $this->wxvehicle_order_query($parklog['orderid']);

            } else {
                $re_param['return_code'] = "FAIL";
                $re_param['return_msg'] = $pay_xml['err_code_des'];
            }

        } else {
            $re_param['return_code'] = "FAIL";
            $re_param['return_msg'] = $pay_xml['return_msg'];
        }
        if ($re_param) {
            if ($re_param['return_code'] == "FAIL") {
                $option = [
                    'key' => $parkinfo['parkkey'],
                    'parkno' => $parkinfo['parkno'],

                ];
                $Carapi = new EtpCar($option);
                $params['machno'] = $parklog['outno'];
                $params['text'] = "无感支付:" . $re_param['return_msg'];
                $res = $Carapi->up_voice($params);

            }
            return $res;
        }

    }

    public function wxvehicle_order_query($out_trade_no, $orderno = "")
    {
        try {
            $Paylog = new Paylog();
            $payinfo = $Paylog->where(['orderid' => $out_trade_no])->find();
            $Parklog = new Parklog();
            $parklog = $Parklog->where(['id' => $payinfo['oid']])->find();
            $Parkinfo = new Parkinfo();
            $Agent = new Agent();
            $parkinfo = $Parkinfo->where(['id' => $payinfo['parkid']])->find();
            $agentinfo = $Agent->where(['id' => $payinfo['agentid']])->find();
            $weObj = new Wxobjopen(['partnerkey' => $agentinfo['machkey']]);
            $arrdata = array(
                "appid" => $agentinfo['appid'],
                "mch_id" => $agentinfo['machid'],
                'sub_appid' => $parkinfo['micro_appid'],
                "sub_mch_id" => $parkinfo['machid'],
                "nonce_str" => $weObj->generateNonceStr(),
                "sign_type" => "HMAC-SHA256",
                "out_trade_no" => $out_trade_no,
            );
            $urls = "https://api.mch.weixin.qq.com/transit/partnerpay/queryorder";
            $pay_xml = $weObj->createWxPackageXml($arrdata);
            $pay_xml = $weObj->SendPost($urls, $pay_xml);
            file_put_contents('/data2/html/apis/3.txt', "[" . date('Y-m-d H:i:s') . "]" . "订单确认:" . json_encode($pay_xml) . PHP_EOL, 8);

            if ($pay_xml['return_code'] == "SUCCESS") {
                if ($pay_xml['result_code'] == "SUCCESS") {
                    $re_param['return_code'] = "SUCCESS";
                    $re_param['return_msg'] = "支付成功";
                    //抬杆
                    //此处需加入判断是否已出场成功
                    file_put_contents('/data2/html/apis/3.txt', "[" . date('Y-m-d H:i:s') . "]" . "出场结果1:" . json_encode($re_param) . PHP_EOL, 8);
                    if ($pay_xml['trade_state'] == "SUCCESS") {
                        //SUCCESS—支付成功
                        //ACCEPT—已接收，等待扣款
                        //PAY_FAIL--支付失败(其他原因，如银行返回失败)
                        //REFUND—转入退款
                        if ($payinfo['pay_status'] == "N") {

                            $s_data['pay_status'] = "Y";
                            $s_data['payno'] = $pay_xml['transaction_id'];
                            $s_data['pay_status'] = "Y";
                            $s_data['channel'] = "weixin";
                            $s_data['paytype'] = "autopay";
                            $s_data['pay_time'] = date('Y-m-d H:i:s', strtotime($pay_xml['time_end']));
                            $s_data['pay_fee'] = $pay_xml['total_fee'] / 100;
                            $s_data['payinfo'] = json_encode($payinfo);
                            $Paylog->save($s_data, ['id' => $payinfo['id']]);
                            $Parklog = new Parklog();
                            $Parklog->save(['paystatus' => 'Y', 'channel' => "weixin"], ['id' => $payinfo['oid']]);
                            $param['payno'] = $pay_xml['transaction_id'];
                            $param['OrderNo'] = $payinfo['orderno'];
                            $param['out_trade_no'] = $pay_xml['out_trade_no'];
                            $param['channel'] = "weixin";
                            $param['paytype'] = "autopay";
                            $resp = $this->payresult($param, $parkinfo);
                            file_put_contents('/data2/html/apis/3.txt', "[" . date('Y-m-d H:i:s') . "]" . "出场结果2:" . json_encode($resp) . PHP_EOL, 8);

                        }
                    }elseif($pay_xml['trade_state'] == "ACCEPT"){
                        $re_param['return_code']="";
                        $re_param['return_msg']="";

                    } else {

                        $re_param['return_code'] = "FAIL";
                        $re_param['return_msg'] = "无感支付失败";

//                        $this->wxvehicle_order_query($out_trade_no, $orderno);
                    }

                } else {
                    $re_param['return_code'] = "FAIL";
                    $re_param['return_msg'] = $pay_xml['err_code_des'];
                }

            }
        } catch (\Exception $e) {
            $re_param['return_code'] = "FAIL";
            $re_param['return_msg'] = $e->getMessage();
            file_put_contents('/data2/html/apis/3.txt', "[" . date('Y-m-d H:i:s') . "]" . "出场结果debug:" . json_encode($re_param) . PHP_EOL, 8);

        }
//        if ($re_param['return_code'] == "FAIL") {
//            $option = [
//                'key' => $parkinfo['parkkey'],
//                'parkno' => $parkinfo['parkno'],
//
//            ];
//            $Carapi = new EtpCar($option);
//            $params['machno'] = $parklog['outno'];
//            if (isset($pay_xml['err_code_des'])) {
//                $params['text'] = "无感支付:" . $pay_xml['err_code_des'];
//            } else {
//                $params['text'] = "支付失败";
//            }
//            $res = $Carapi->up_voice($params);
//
//        }
        return $re_param;


    }

    public function payresult($param, $parkinfo)
    {
        try {

            $orderno = $param['OrderNo'];

            $params['orderno'] = $orderno;
            $params['channel'] = $param['channel'];
            $params['paytype'] = $param['paytype'];
            $params['payno'] = $param['payno'];
            $params['outtradeno'] = $param['out_trade_no'];
            $params['paystatus'] = "OK";
            $option = [
                'key' => $parkinfo['parkkey'],
                'parkno' => $parkinfo['parkno'],
            ];

            $Carapi = new EtpCar($option);
            $res = $Carapi->up_pay_notify($params);
        } catch (\Exception $e) {
            $res['return_code'] = "FAIL";
            $res['return_msg'] = $e->getMessage();
        }
        return $res;
    }

}